//
//  testtable.m
//  testvideo
//
//  Created by fcbayern on 2020/12/20.
//  Copyright © 2020 fcbayern. All rights reserved.
//

#import "testtable.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "vediocell.h"
#import <objc/runtime.h>
#import "commentview.h"
#import "Single.h"


@interface testtable ()
@property (nonatomic, strong) UITableView *tableView;
@property(strong,nonatomic)NSMutableArray * avarray;
@property(strong,nonatomic)NSMutableArray * likearray;
@property(strong,nonatomic)UITextField *textField1;
@property NSInteger tempnumber;
@property int checkcomment;
@property(strong,nonatomic)NSString * vedioid;
@property(strong,nonatomic)NSString * tempurl;
@property (weak, nonatomic)AVPlayer *myPlayer;//播放器
@property (strong, nonatomic)AVPlayerItem *item;//播放单元
@property (weak, nonatomic)AVPlayerLayer *playerLayer;//播放界面（layer）

@end

@implementation testtable

-(void)viewWillAppear:(BOOL)animated{
     _avarray = [[NSMutableArray alloc]init];
     _likearray = [[NSMutableArray alloc]init];
    _tempurl = @"http://106.52.91.37:8081/api/video/";
    NSString * url1 =[[NSString alloc] initWithFormat:@"%@%@",_tempurl,@"all"];
    AFHTTPSessionManager * manager1 = [AFHTTPSessionManager manager];
    manager1.responseSerializer = [AFJSONResponseSerializer serializer];
    manager1.requestSerializer = [AFJSONRequestSerializer serializer];
    ((AFJSONResponseSerializer *)manager1.responseSerializer).removesKeysWithNullValues = YES;
    [manager1 GET:url1 parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(responseObject != nil){
            [self.avarray removeAllObjects];
            [self.likearray removeAllObjects];
            NSDictionary * returnjson = (NSDictionary *)responseObject;
            NSDictionary * Data =(NSDictionary * )returnjson[@"Message"];

            for(id key in Data){
                NSString * tempvediourl = [[NSString alloc] initWithFormat:@"%@%@%@",self->_tempurl,@"public/",key[@"URL"]];
                NSMutableArray * tempcomment = key[@"Comments"];
                [[Single sharedInstance].commentlist addObject: tempcomment];
                [self.avarray addObject:tempvediourl];
                [self.likearray addObject:key[@"Vid"]];
            }
            self->_vedioid = _likearray[0];
            [self->_tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    _checkcomment = 0;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor =[UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(self.view);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
        make.centerX.equalTo(self.view.mas_centerX);
        
    }];
    _tableView.pagingEnabled = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollsToTop = NO;
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.frame = self.view.bounds;
    _tableView.rowHeight = _tableView.frame.size.height/3;
    _tableView.scrollsToTop = NO;
    _tempnumber = 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return self.view.frame.size.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _avarray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    vediocell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellid"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell = [[vediocell alloc] init];
    }
    if(indexPath.row == 0){
        NSURL *localVideoUrl = [NSURL URLWithString:_avarray[0]];
        self.item = [AVPlayerItem playerItemWithURL:localVideoUrl];
        self.myPlayer = [AVPlayer playerWithPlayerItem:self.item];
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.myPlayer];
        self.playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
        cell.playerLayer = _playerLayer;
        [cell.contentView.layer addSublayer:cell.playerLayer];
        [_myPlayer play];
        UIButton * comment = [[UIButton alloc]initWithFrame:CGRectMake(340, 570, 50, 50)];
        UIButton * like = [[UIButton alloc]initWithFrame:CGRectMake(340, 650, 50, 50)];
        UIButton * collect = [[UIButton alloc]initWithFrame:CGRectMake(340, 490, 50, 50)];
        
        [collect addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
        [like addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
        [comment addTarget:self action:@selector(seecomment:) forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
        
        [like setImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
        [collect setImage:[UIImage imageNamed:@"collect1"] forState:UIControlStateNormal];
        [comment setImage:[UIImage imageNamed:@"comment1"] forState:UIControlStateNormal];
        
        
        [cell.contentView addSubview:comment];
        [cell.contentView addSubview:like];
        [cell.contentView addSubview:collect];
        [cell.contentView bringSubviewToFront: comment];
        [cell.contentView bringSubviewToFront: like];
        [cell.contentView bringSubviewToFront: collect];
        
        
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    vediocell * mytempcell2;
    mytempcell2 = [vediocell alloc];
    mytempcell2 = [_tableView cellForRowAtIndexPath:indexPath];
    [mytempcell2.playerLayer.player pause];
    
    UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"请发布评论" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction;
    UIAlertAction *okAction;
    
    cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [mytempcell2.playerLayer.player play];
    }];
    okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString * text = _textField1.text;
        if(_textField1.text.length == 0){
            UIAlertController * alert2 = [UIAlertController alertControllerWithTitle:@"提示" message:@"评论不能为空" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert2 animated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
            });
            
        }
        else{
            NSString * urlcomment =[[NSString alloc] initWithFormat:@"%@%@",self->_tempurl,@"comment"];
            AFHTTPSessionManager * manager3 = [AFHTTPSessionManager manager];
            manager3.responseSerializer = [AFJSONResponseSerializer serializer];
            manager3.requestSerializer = [AFJSONRequestSerializer serializer];
            NSDictionary * parameters = @{
                @"videoid": _vedioid,
                @"content": text
            };
            
            [manager3 POST:urlcomment parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"%@",error);
            }];
            UIAlertController * alert2 = [UIAlertController alertControllerWithTitle:@"提示" message:@"评论成功" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert2 animated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
            });
        }
        [mytempcell2.playerLayer.player play];
    }];
    [alert1 addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Login";
        _textField1 = textField;
        
    }];
    [alert1 addAction:okAction];
    [alert1 addAction:cancelAction];
    [self presentViewController:alert1 animated:YES completion:nil];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
   vediocell * mytempcell2;
    mytempcell2 = [vediocell alloc];
     NSIndexPath *indexPath=[NSIndexPath indexPathForRow:_tempnumber inSection:0];
     mytempcell2 = [_tableView cellForRowAtIndexPath:indexPath];
    mytempcell2.myPlayer = nil;
    [mytempcell2.playerLayer.player pause];
    
    vediocell * mytempcell3;
    mytempcell3 = [vediocell alloc];
     NSIndexPath *indexPath2=[NSIndexPath indexPathForRow:0 inSection:0];
     mytempcell3 = [_tableView cellForRowAtIndexPath:indexPath2];
    mytempcell3.myPlayer = nil;
    [mytempcell3.playerLayer.player pause];
    [mytempcell3.playerLayer removeFromSuperlayer];
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
}



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat contentYoffset = scrollView.contentOffset.y;
    NSInteger j =  contentYoffset/self.view.frame.size.height;
    NSURL *localVideoUrl = [NSURL URLWithString:_avarray[j]];
    self.item = [AVPlayerItem playerItemWithURL:localVideoUrl];
    self.myPlayer = [AVPlayer playerWithPlayerItem:self.item];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.myPlayer];
    vediocell * mytempcell;
    mytempcell = [vediocell alloc];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:j inSection:0];
    mytempcell = [_tableView cellForRowAtIndexPath:indexPath];
    self.playerLayer.frame = CGRectMake(0, 100, mytempcell.contentView.bounds.size.width, 500);
    mytempcell.playerLayer = self.playerLayer;
    [mytempcell.contentView.layer addSublayer:mytempcell.playerLayer];
    
    
    UIButton * comment = [[UIButton alloc]initWithFrame:CGRectMake(340, 570, 50, 50)];
    UIButton * like = [[UIButton alloc]initWithFrame:CGRectMake(340, 650, 50, 50)];
    UIButton * collect = [[UIButton alloc]initWithFrame:CGRectMake(340, 490, 50, 50)];
    [collect addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
    [like addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
    [comment addTarget:self action:@selector(seecomment:) forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
    
    [like setImage:[UIImage imageNamed:@"like"] forState:UIControlStateNormal];
    [collect setImage:[UIImage imageNamed:@"collect1"] forState:UIControlStateNormal];
    [comment setImage:[UIImage imageNamed:@"comment1"] forState:UIControlStateNormal];
    
    [mytempcell.contentView addSubview:comment];
    [mytempcell.contentView addSubview:like];
    [mytempcell.contentView addSubview:collect];
    [mytempcell.contentView bringSubviewToFront: comment];
    [mytempcell.contentView bringSubviewToFront: like];
    [mytempcell.contentView bringSubviewToFront: collect];
    
    
    
    _tempnumber = j;
    _vedioid = _likearray[j];
    [_myPlayer play];
}

-(void)like:(UIButton*)sender {
    [sender setImage:[UIImage imageNamed:@"like2"] forState:UIControlStateNormal];
    NSString * urllike = [[NSString alloc] initWithFormat:@"%@%@",self->_tempurl,@"like"];
    AFHTTPSessionManager * manager2 = [AFHTTPSessionManager manager];
    manager2.responseSerializer = [AFJSONResponseSerializer serializer];
    manager2.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary * parameters = @{
        @"videoid": _vedioid
    };
    [manager2 POST:urllike parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

-(void)collect:(UIButton*)sender {
    [sender setImage:[UIImage imageNamed:@"collect2"] forState:UIControlStateNormal];
    NSString * urlstar = [[NSString alloc] initWithFormat:@"%@%@",self->_tempurl,@"star"];
    AFHTTPSessionManager * manager2 = [AFHTTPSessionManager manager];
    manager2.responseSerializer = [AFJSONResponseSerializer serializer];
    manager2.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary * parameters = @{
        @"videoid": _vedioid
    };
    [manager2 POST:urlstar parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}


-(void)seecomment:(UIButton*)sender {
   [sender setImage:[UIImage imageNamed:@"comment2"] forState:UIControlStateNormal];
   NSString * url1 =[[NSString alloc] initWithFormat:@"%@%@",_tempurl,@"all"];
   AFHTTPSessionManager * manager1 = [AFHTTPSessionManager manager];
   manager1.responseSerializer = [AFJSONResponseSerializer serializer];
   manager1.requestSerializer = [AFJSONRequestSerializer serializer];
    ((AFJSONResponseSerializer *)manager1.responseSerializer).removesKeysWithNullValues = YES;
   [manager1 GET:url1 parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
       
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       [[Single sharedInstance].commentlist removeAllObjects];
       NSDictionary * returnjson = (NSDictionary *)responseObject;
       NSDictionary * Data =(NSDictionary * )returnjson[@"Message"];

       for(id key in Data){
           NSString * tempvediourl = [[NSString alloc] initWithFormat:@"%@%@%@",self->_tempurl,@"public/",key[@"URL"]];
           NSMutableArray * tempcomment = key[@"Comments"];
           [[Single sharedInstance].commentlist addObject: tempcomment];
       }
       NSLog(@"%@",[Single sharedInstance].commentlist);
       [[Single sharedInstance].singlecomment removeAllObjects];
       NSMutableArray * tempdic =[Single sharedInstance].commentlist[_tempnumber];
       for(int i = 0;i<tempdic.count;++i){
           [[Single sharedInstance].singlecomment addObject: tempdic[i]];
       }
       vediocell * mytempcell2;
       mytempcell2 = [vediocell alloc];
       NSIndexPath *indexPath=[NSIndexPath indexPathForRow:_tempnumber inSection:0];
       mytempcell2 = [_tableView cellForRowAtIndexPath:indexPath];
       [mytempcell2.playerLayer.player pause];
       commentview * newview = [[commentview alloc]init];
       newview.modalPresentationStyle = UIModalPresentationFormSheet;
       [self presentViewController:newview animated:YES completion:nil];
       newview.view.superview.bounds = CGRectMake(0.0, 300, 560, 500);
       
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       NSLog(@"%@",error);
   }];
    
    
    
}
@end
